import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import axios from 'axios'

interface User {
  id: number
  userName: string
  nickName: string
  account: string
  avatar: string
  token: string
}

export const useUserStore = defineStore('user', () => {
  const user = ref<User | null>(null)
  const token = ref<string>('')
  const error = ref<string>('')
  const isAuthenticated = computed(() => !!token.value)
  // 初始化时从本地存储加载
  const initFromStorage = () => {
    const storedUser = localStorage.getItem('user')
    if (storedUser) {
      user.value = JSON.parse(storedUser)
      token.value = user.value?.token || ''
    }
  }

  const login = async (username: string, password: string) => {
    try {
      const response = await axios.post('http://localhost:8080/user/login', {
        userName: username,
        password
      })
      
      if (response.data.code === "0") {
        user.value = {
          ...response.data.data,
          nickName: response.data.data.nickName // 保持字段一致性
        }
        token.value = response.data.data.token
        localStorage.setItem('user', JSON.stringify(user.value))
        return true
      }
      return false
    } catch (err) {
      error.value = '登录失败，请检查用户名和密码'
      return false
    }
  }

  const logout = () => {
    user.value = null
    token.value = ''
    localStorage.removeItem('user')
  }

  // 初始化加载
  initFromStorage()

  return { user, token, error, login, logout, isAuthenticated  }
})